package com.chaos.auth.config.granter.user;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.chaos.auth.api.constant.CommonConstant;
import com.chaos.auth.api.dto.token.UserAuthenticationToken;
import com.chaos.auth.service.userdetails.UserByAliOpenIdDetailsService;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.model.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Slf4j
@Component
public class UserByAliAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserByAliOpenIdDetailsService userByAliOpenIdDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        String code = details.get("code");
        Long tenantId = Long.valueOf(details.get("tenantId"));
        String phoneNumber = details.get("phoneNumber");

        Assert.notNull(code, "code不能为空");
        Assert.notNull(tenantId, "租户不能为空");
        Assert.notNull(phoneNumber, "手机号不能为空");


        UserDetails userDetails = userByAliOpenIdDetailsService.loadUserByAliOpenId(code, null);
        UserAuthenticationToken result = new UserAuthenticationToken(userDetails);
        result.setDetails(authentication.getDetails());
        return result;
    }




    @Override
    public boolean supports(Class<?> authentication) {
        return UserAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
